#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;


int test1()
{
    pid_t id = fork();
    if(id == 0)     // child_process
    {
        int cnt = 5;
        while(cnt)
        {
            printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
            --cnt;
        }
        printf("turning to execl of 'ls'...\n");
        execl("/usr/bin/ls", "ls", "-l", "-a", NULL);
        
        exit(1);    // execl run error can return exit(1), else not
    }

    // father_process
    int status = 0;
    int count = 0;
    while(true)
    {
        pid_t rid = waitpid(id, &status, WNOHANG);
        if(rid > 0)
        {
            printf("wait success, rid: %d, status: %d, exit code: %d\n", rid, status, 
                                                            WEXITSTATUS(status));
            break;
        }
        else if(rid == 0)
        {
            printf("Waiting: child is running...\n");
            count++;        // father_process can do other things
        }
        else{
            perror("waitpid");
            break;
        }
        usleep(200);
    }
    cout << "father process add_count = " << count << endl;
    
    return 0;
}

int main()
{
    int r1 = test1();
    return r1;
}
